import os
import re
import socket

from rest_framework.response import Response

# 自动获取本机ip
def get_ip():
    try:
        connection = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        connection.connect(('8.8.8.8',80))
        ip = connection.getsockname()[0]
    except Exception as e:
        pass
    finally:
        connection.close()
    return ip


    # 验证参数
def verify_params(request, *args, **kwargs):
    content_type = request.META['CONTENT_TYPE']
    authorization = request.META['HTTP_AUTHORIZATION']
    if not all(['content_type', 'authorization']):
        response = {"message": "缺少必传参数", 'success': False}
    if re.match(r'^JWT[\s][\w+]\.[\w+]\.[\w+]', authorization):
        response = {"message": "参数HTTP_AUTHORIZATION有误",
                    "success": False}
    if content_type != "application/json;charset=UTF-8":
        response = {"message": "参数content_type有误",
                    "success": False}
    return response



# 读取并修改fdfs.client配置文件
# def conf():
#     path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
#     file_path = os.path.join(path, 'utils/fastdfs/client.conf')
#     # 自动生成的log 文件夹
#     logpath = os.path.join(path, 'logs')
#     base_path = 'base_path='+logpath + '\n'
#     # logs_dir = os.path.join(file_pth, 'logs')
#     ip_address = 'tracker_server=' + get_ip() + ':22122\n'
#
#     with open(file_path, 'r') as file:
#         content_list = file.readlines()
#         index_len = len(content_list)
#         index = [i for i in range(index_len)]
#         content_dict = zip(index, content_list)
#         for key, value in content_dict:
#             if re.match(r'^base_path=/', value):
#                 value = base_path
#             if re.match(r'^tracker_server', value):
#                 value = ip_address
#
#
#         i = -1
#         for content in content_list:
#             if re.match(r'^base_path=/', content):
#                 content_list.pop(i)
#                 content_list.append(base_path)
#                 continue
#             if re.match(r'^tracker_server', content):
#                 content_list.pop(i)
#                 content_list.append(ip_address)
#                 continue
#             else:
#                 i += 1
#
#     with open(file_path, 'w+') as file:
#         for str00 in content_list:
#             file.write(str00)
